package simple.utils.data;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 10/8/13
 * Time: 2:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class LargeBytes {

    private final byte[][] arrays;

    public LargeBytes(byte[]... arrays) {
        this.arrays = arrays;
    }

    /**
     * Get buffer of bytes from index
     *
     * @param index  index
     * @param buffer byte array to fill
     */
    public void get(long index, byte[] buffer) throws IOException {
        long end = index + buffer.length;
        int startBuf = inBuf(index);
        int endBuf = inBuf(end);
        if (startBuf == -1 || endBuf == -1) {
            throw new IOException("Out of range - (" + index + "," + end + ")");
        }
        if (startBuf == endBuf) {
            // read all from first buffer
            read(startBuf, index, buffer, 0, buffer.length);
        } else {
            // read part from first buffer
            int fromFirst = (int) (MultiMappedFile.MAX_BUF_SIZE - (index % MultiMappedFile.MAX_BUF_SIZE));
            read(startBuf, index, buffer, 0, fromFirst);
            // rest from last buffer
            read(endBuf, 0, buffer, fromFirst, buffer.length - fromFirst);
        }
    }

    private void read(int bufIndex, long absoluteIndex, byte[] buffer, int offset, int readSize) {
        int bufStart = (int) (absoluteIndex % MultiMappedFile.MAX_BUF_SIZE);
        byte[] b = arrays[bufIndex];
        System.arraycopy(arrays[bufIndex], bufStart, buffer, offset, readSize);
    }

    private int inBuf(long index) {
        int bufIndex = (int) (index / MultiMappedFile.MAX_BUF_SIZE);
        if (bufIndex >= arrays.length) {
            return -1;
        }
        return bufIndex;
    }


}
